# 引入必要的库

import numpy as np
import yaml
import os
import time
import cv2
from joblib import dump as dp, load as ld

yaml_file_path = '0_setting.yaml'


# 获取 0_setting.yaml 中的键 key 对应的值 value
def get(key):
    with open(yaml_file_path, 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)
        value = data.get(key, None)
        return value


# 预处理图像, 把图像设置为指定大小之后，展平返回
def preprocess_image(file_name, new_size):
    # 1. 读取图像灰度图
    #file_name = os.path.abspath(file_name)
    #img = cv2.imread(file_name, cv2.IMREAD_GRAYSCALE)
    img = cv2.imdecode(np.fromfile(file_name), cv2.IMREAD_GRAYSCALE)
    #if img is None:
        #return ValueError(f"Unable to load image {file_name}")
    # 2. 调整图像大小为 new_size
    img = cv2.resize(img, new_size)
    # 3. 将图像展平为一维数组
    #img = img.flatten()
    return img




# 用joblib把叫做 name 的对象 obj 保存(序列化)到位置 loc
def dump(obj, name, loc):
    start = time.time()
    print(f"把{name}保存到{loc}")
    dp(obj, loc)
    end = time.time()
    print(f"保存完毕,文件位置:{loc}, 大小:{os.path.getsize(loc) / 1024 / 1024:.3f}M")
    print(f"运行时间:{end - start:.3f}秒")


# 用joblib读取(反序列化)位置loc的对象obj,对象名为name
def load(name, loc):
    print(f"从{loc}提取文件{name}")
    obj = ld(loc)
    return obj

